package com.daiyang.campus_lucky_draw.service.impl;

import com.daiyang.campus_lucky_draw.common.error.ServiceErrorCodeConstants;
import com.daiyang.campus_lucky_draw.common.exception.ServiceException;
import com.daiyang.campus_lucky_draw.common.utils.*;
import com.daiyang.campus_lucky_draw.service.VerificationCodeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class VerificationCodeServiceImpl implements VerificationCodeService {
    private static final String VERIFICATION_CODE_PREFIX =
            "verification_code_";
    private static final Integer VERIFICATION_CODE_EFFECTIVE_TIME = 60;
    private static final String VERIFICATION_TEMPLATE_CODE = "SMS_465324787";
    @Autowired
    private SMSUtil smsUtil;
    @Autowired
    private RedisUtil redisUtil;
    @Override
    public void sendVerificationCode(String phoneNumber) {

// ⼿机号格式校验
        if (!StringUtils.hasText(phoneNumber)
                || !RegexUtil.checkMobile(phoneNumber)) {
            throw new
                    ServiceException(ServiceErrorCodeConstants.PHONE_NUMBER_ERROR);
        }
        // 创建并发送验证码
        String code = CaptchaUtil.generateCaptchaCode(4);
        Map<String, String> templateParam = new HashMap<>();
        templateParam.put("code", code);
        smsUtil.sendMessage(VERIFICATION_TEMPLATE_CODE,
                phoneNumber, JacksonUtil.writeValueAsString(templateParam));
        // 验证码存⼊缓存
        redisUtil.set(VERIFICATION_CODE_PREFIX + phoneNumber, code,
                VERIFICATION_CODE_EFFECTIVE_TIME);
    }
    @Override
    public String getVerificationCode(String phoneNumber) {
        // ⼿机号格式校验
        if (!StringUtils.hasText(phoneNumber)
                || !RegexUtil.checkMobile(phoneNumber)) {
            throw new
                    ServiceException(ServiceErrorCodeConstants.PHONE_NUMBER_ERROR);
        }
        return (String) redisUtil.get(VERIFICATION_CODE_PREFIX + phoneNumber);
    }
}